package com.tarena.practice.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tarena.practice.common.util.CookieUtils;
import com.tarena.practice.common.vo.SysResult;
import com.tarena.practice.web.pojo.User;
import com.tarena.practice.web.service.UserService;
@Controller
public class UserController {
	/*
	 * 注册方法
	 */
	@Autowired
	private UserService userService;
	// 跳转注册
	@RequestMapping("/user/doRegister")
	@ResponseBody
	public SysResult doRegister(User user){
		try {
			System.out.println(user);
			userService.doRegister(user);
			SysResult result=new SysResult();
			return SysResult.build(200, "激活邮件已发送至您的邮箱 !请登录邮箱,完成最终注册激活!");
		} catch (Exception e) {
			return SysResult.build(201, "注册失败");
		}
	}
	
	@RequestMapping("/user/checkUsername")
	@ResponseBody
	public SysResult checkUsername(String username){
		try {
			Boolean isHave=userService.checkUsername(username);
//			boolean isHave=false;
			return SysResult.oK(isHave);
		} catch (Exception e) {
			return SysResult.build(201, "失败了");
		}
	}
	
	/*
	 * 用户注册激活邮箱校验
	 * http://localhost:8092/user/activatEmail?
	 * code=887e852c03ee4e6bb33d0832934dcf4aa111&email=592575258@qq.com
	 * 这里的id是32位UUID+username
	 * 搜索username和对应email，就可以设置激活该账户了
	 */
	@RequestMapping("/user/activatEmail/{code}/{email}")
	@ResponseBody
	public SysResult checkEmail(@PathVariable String code,@PathVariable String email){
		try{
		userService.activeByUsernameAndEmail(code.substring(32),email);
		return SysResult.oK();
		}catch(Exception e){
			return SysResult.build(201, "激活失败");
		}
	}
	
	
	/*
	 * 登录请求
	 */
	@RequestMapping("/user/doLogin")
	@ResponseBody
	public SysResult doLogin(User user,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception{
//	//user传给service,调用http访问sso
//		System.out.println("121111111111111");
//	String ticket=userService.doLogin(user);
//	//ticket是否为空; 只要是null或者""都是false
//	if(StringUtils.isNotEmpty(ticket)){
//		//表示登录成功,将ticket写进cookie
//		//common中封装了cookie的各种方法
//		//COOKIE中的key定义为JT_TICKET
//		CookieUtils.setCookie(request, response, 
//				"JT_TICKET", ticket);
//		return SysResult.oK();
//	}else{//登录失败,ticket是空
//		return SysResult.build(201, "登录密码或密码错误,请重新输入");
//	}
		return SysResult.oK();
	}
}
